package org.example.myleet.p819;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

public class Solution {
    public String mostCommonWord(String paragraph, String[] banned) {
        char[] charArr = paragraph.toCharArray();
        HashMap<String, Integer> wordCount = new HashMap<>();
        Set<String> bannedWords = Arrays.stream(banned).collect(Collectors.toSet());
        StringBuilder word = new StringBuilder();
        int maxAppearance = 0;
        for (char c : charArr) {
            if (Character.isAlphabetic(c)) {
                word.append(Character.toLowerCase(c));
            } else {
                if (word.length() > 0) {
                    String w = word.toString();
                    word.delete(0, word.length());
                    if (!bannedWords.contains(w)) {
                        Integer count = wordCount.computeIfAbsent(w, key -> 0);
                        ++count;
                        maxAppearance = Math.max(maxAppearance, count);
                        wordCount.put(w, count);
                    }
                }
            }
        }
        if (word.length() > 0) {
            String w = word.toString();
            word.delete(0, word.length());
            if (!bannedWords.contains(w)) {
                Integer count = wordCount.computeIfAbsent(w, key -> 0);
                ++count;
                maxAppearance = Math.max(maxAppearance, count);
                wordCount.put(w, count);
            }
        }
        String maxAppearanceWord = "";
        for (Map.Entry<String, Integer> entry : wordCount.entrySet()) {
            if (maxAppearance == entry.getValue()) {
                maxAppearanceWord = entry.getKey();
                break;
            }
        }
        return maxAppearanceWord;
    }
}
